import React from 'react';
import '../../../assets/scss/components/general/yandexAPI/organization.scss'
import axios from "axios";

const YANDEX_API_URL = 'https://search-maps.yandex.ru/v1';
const API_KEY_SEARCH_YANDEX = '49c6204f-1bc7-4b89-a192-72c691cfefba';

class Organization extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      open: '',
      value: '',
      list: [],
      clicked: 0
    };
    this.orgzContainer = React.createRef();
  };

  componentDidMount() {
    document.addEventListener('mousedown', this.handleClickOutside);
  }

  componentWillUnmount() {
    document.removeEventListener('mousedown', this.handleClickOutside);
  }

  getOrganizationCoords = data => {
    axios.get(`${YANDEX_API_URL}/?text=${data}&lang=ru_RU&apikey=${API_KEY_SEARCH_YANDEX}`)
      .then(response => {
        if (!response.error) {
          this.setState({
            list: response.data.features || []
          })
        } else {
          console.error(response.error)
        }
      }).catch(error => {
      console.error(error.message)
    })
  }

  handleClickOutside = e => {
    if (this.orgzContainer.current && !this.orgzContainer.current.contains(e.target)) {
      this.setState({
        open: false
      })
      if (this.state.clicked === 1){
        this.setState({
          value: ''
        })
        this.props.onChange && this.props.onChange('')
      }

    }
  }

  handleOnChange = e => {

    this.setState({value: e.target.value, clicked: 1})
    this.props.onChange && this.props.onChange(e.target.value)

    if (e.target.value.length >= 3) {
      this.getOrganizationCoords(e.target.value)
      if (!this.state.open) this.setState({open: true})
    }
  }

  handleClick = item => {
    this.setState({
      open: false,
      value: item.properties.name,
      clicked: 3
    })
    this.props.onClick && this.props.onClick(item)
  }

  handleClickAvInput = (e) => {
    if (e.target.value.length >= 3) {
      this.getOrganizationCoords(e.target.value)
      this.setState({open: true})
    }
  }

  render() {
    return (
      <React.Fragment>
        <div className={`orgz-result-container`} ref={this.orgzContainer}>
          <div className="suggest-options-block">
            <input
              className={`location-input ${this.props.className} ${this.props.required ? 'custom-input-invalid' : ''}`}
              type="text"
              name={this.props.id}
              id={this.props.id}
              placeholder={this.props.placeholder}
              autoComplete="off"
              value={this.props.value || this.state.value}
              onChange={this.handleOnChange}
              onClick={this.handleClickAvInput}
              required={this.props.required}
              disabled={this.props.disabled}
            />
            <div className="invalid-feedback">Выберите место</div>
          </div>
          {this.state.list.length > 0 && this.state.open &&
          <div className={`orgz-result ${this.props.required ? 'input-invalid' : ''}`}>
            <ul>
              {this.state.list.map((item, index) => {
                if (item.properties && index < 5) {
                  return (
                    <li
                      key={index}
                      onClick={() => this.handleClick(item)}
                    >
                      <p>{item.properties.name}</p>
                      <span>{item.properties.description}</span>
                    </li>
                  )
                }
              })}
            </ul>
          </div>
          }
        </div>
      </React.Fragment>
    )
  }
}

export default Organization
